/* create by Xujiaixong in 2017/8/2 */
//'use strict'


//海康视频控件初始化参数
//if (!!window.ActiveXObject || "ActiveXObject" in window){//IE
	var hikParamScript =  document.createElement("script");
	hikParamScript.type = "javascript";
	hikParamScript.id = "HIK";
	hikParamScript["for"] = "preview";
	hikParamScript.event = "MsgNotify(iMsg,iError,szDetail,lWnd,szIndexCode)";
	var hikParam = 'if (iMsg == 0x02000007)'
	+'{'		
	+'var _toolbar = "<?xml version=\"1.0\" encoding=\"utf-8\"?>'

	+'<ToolBar><Item type=\"0\" /><Item type=\"24\" /><Item type=\"5\" /><Item type=\"6\" />'

	+'<Item type=\"7\" /><Item type=\"8\" /><Item type=\"9\" /><Item type=\"10\" />'

	+'<Item type=\"12\" /><Item type=\"17\" /><Item type=\"20\" /><Item type=\"21\" />'

	+'<Item type=\"22\" /><Item type=\"53\" /><Item type=\"54\" /></ToolBar>";'

	+'preview.SetToolBar(_toolbar);'
	+'preview.SetToolBarAlwaysShow(0);'
	+'preview.SetInstPlayCfg(30);'

	+'var _snap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>'
	+'<SnapShot><PicType>jpeg</PicType><Quality>80</Quality><SnapMulti>1</SnapMulti><SnapTimes>3</SnapTimes>'
	+'<TimeSpan>1</TimeSpan><SaveFolder>C:\\Users\\lichanghua\\Documents\\CSC\\capture\\</SaveFolder><KeyWords></KeyWords></SnapShot>";'
	+'preview.SetSnapParam(_snap);'

	+'var _record = "<?xml version=\"1.0\" encoding=\"utf-8\"?><VideoRecord><PackType>0</PackType><MaxRecTime>0</MaxRecTime>'
	+'<PackTime>100</PackTime><PackSize>100</PackSize>'
	+'<SaveFolder>C:\\Users\\lichanghua\\Documents\\CSC\\record\\</SaveFolder><KeyWords></KeyWords></VideoRecord>";'
	+'preview.SetRecordParam(_record);'
	+'}';
	hikParamScript.innerHTML = hikParam;
	var ohead=document.getElementsByTagName("head")[0];
	ohead.appendChild(hikParamScript);
	$("#HIK").attr("for","preview");
//} 


//萤石云视频需要的js
document.write('<script src="https://open.ys7.com/sdk/js/1.1/ezuikit.js"></script>');

//各个摄像头厂家的接口实例
//var HWOCX = null;
// 生产控件
var videoControlFactoryFather = function(){
	this.videoControl = null;
	this.videoControlH = null;
	this.videoControlD = null;
	this.videoControlNVR = null;
	this.videoControlHW = null;
	this.videoControlH82 = null;
	this.VH82Count = 0;
	this.VDCount = 0;
	this.VHCount = 0;
	this.VNCount = 0;
	this.HWCount = 0;
	this.wndCountD = 0;
	this.wndCountH = 0;
	this.wndCountN = 0;
	this.wndCountHW = 0;
	this.wndCountH82 = 0; 	
	this.strHTML = '';
	this.domD = null;
	this.domH = null;
	this.domN = null;
	this.domHW = null;
	
	//各个摄像头厂家的接口实例
	//this.HWOCX = null;
}

var videoControlFactory = function(){
	videoControlFactoryFather.call(this);
};

videoControlFactory.prototype.createVideo = function(containObj,deviceinfo){

	this.VDCount = 0;
	this.VHCount = 0;
	this.VNCount = 0;
	this.HWCount = 0;
	this.wndCountD = 0;
	this.wndCountH = 0;
	this.wndCountN = 0;
	this.wndCountHW = 0;
	this.strHTML = '';
	this.domD = null;
	this.domH = null;
	this.domN = null;
	this.domHW = null;	

	var videosInfo = [];

	if(deviceinfo && deviceinfo.length){
		videosInfo = deviceinfo;
	} else {
		videosInfo.push(deviceinfo);
	}

	//判断各个类型的视频数量各多少
	for(var j=0;j<videosInfo.length;j++){
		if(videosInfo[j].apicode == "VH1.0"){
			this.VHCount++;
		} else if(videosInfo[j].apicode == "VD1.0"){
			this.VDCount++;
		} else if(videosInfo[j].apicode == "VD5252"){
			this.VNCount++;
		} else if(videosInfo[j].apicode == "HW1.0"){
			this.HWCount++;
		} else if(videosInfo[j].apicode == "VH8200"){
			this.VH82Count++;
		}
	}

	
	if(this.VH82Count > 0){
		if(this.VH82Count == 1){
			this.wndCountH82 = 1
		}
		if(this.VH82Count>1 && this.VH82Count<5){
			this.wndCountH82 = 4
		}
		if(this.VH82Count >4){
			this.wndCountH82 = 9
		}
	}
	if(this.VDCount > 0){
		if(this.VDCount == 1){
			this.wndCountD = 1;
		} else if(this.VDCount<=4){
			this.wndCountD = 4;
		} else if(this.VDCount <= 9){
			this.wndCountD = 9;
		} else {
			this.wndCountD = 12;
		}
	}

	if(this.VHCount > 0){
		if(this.VHCount == 1){
			this.wndCountH = 1;
		} else if(this.VHCount <= 4){
			this.wndCountH = 2;
		} else if(this.VHCount <= 9){
			this.wndCountH = 3;
		} else {
			this.wndCountH = 5;
		}
	}

	if(this.VNCount > 0){
		if(this.VNCount == 1){
			this.wndCountN = 1;
		} else if(this.VNCount<=4){
			this.wndCountN = 4;
		} else if(this.VNCount <= 9){
			this.wndCountN = 9;
		} else {
			this.wndCountN = 12;
		}
	}
	if(this.HWCount > 0) {
		//目前仅一个窗口布局
		this.wndCountHW = 1;
	}
	var classNum = this.getTypeNum(videosInfo)  // 获取视频类型
	if(classNum > 1){
	//出现关联的多个摄像头中既有海康又有大华页面就存在TAB
	if(classNum == 2){
		strHTML = '<header class="tab-v"><span class="active-v">大华视频</span><span>海康视频</span></header>'
		+'<div id="mh-video" >'
		+'<div class="video switch-tab" id="video-D"></div>'
		+'<div class="video switch-tab" id="video-H"></div>'
		+'</div>';		
	} else if (classNum == 3) {
		strHTML = '<header class="tab-v"><span class="active-v">大华视频</span><span>海康视频</span><span>大华NVR视频</span><span>华为视频</span></header>'
		+'<div id="mh-video" >'
		+'<div class="video switch-tab" id="video-D"></div>'
		+'<div class="video switch-tab" id="video-H"></div>'
		+'<div class="video switch-tab" id="video-N"></div>'
		+'<div class="video switch-tab" id="video-HW"></div>'
		+'</div>';
	}

	containObj.innerHTML = strHTML;

	$(".tab-v span").css({
		"display":"inline-block",
		"width":"80px",
		"line-height":"30px",
		"background":"#ccc",
		"color":"#000",
		"font-size":"12px",
		"text-align":"center",
		"font-weight":"bold",
		"cursor":"pointer",
		"margin":"2px 0px 2px 10px",
		"border-radius":"6px",
		"font-family":"\"Microsoft Yahei\",\"Hiragino Sans GB\",\"Helvetica Neue\""
	});
	$(".active-v").css({
		"background":"#333333",
		"color":"#fff"
	});
	$("#mh-video").css("height","calc(100% - 34px)");
	$(".video").css("height","100%");
	
	this.domD = document.getElementById("video-D");
	this.domH = document.getElementById("video-H");
	this.domN = document.getElementById("video-N");
	this.domHW = document.getElementById("video-HW");
	$(".tab-v span").click(function(){			            
		$(this).css({
			"background":"#333333",
			"color":"#fff"
		}).siblings().css({
			"background":"#ccc",
			"color":"#000"
		});
		var index = $(this).index();
		$(".switch-tab").hide(); 
		$(".switch-tab").eq(index).show(); 

	});
} else { //摄像头类型只有一个的情况(通常一次打开一个摄像头进行预览)
	
	var dh = document.getElementById("DPSDK_OCX"); //大华
	var hk = document.getElementById("preview");   //海康
	var nvr = document.getElementById("ocx");      //大华NVR

	//多个控件同时存在时清空容器,只有一个控件存在时不清空容器，保存用户信息
	if(!( (dh && !hk && !nvr ) || (hk && !dh && !nvr ) || (nvr && !hk && !dh )|| (!nvr && !hk && !dh ) )){
	    containObj.innerHTML = "";
	}
}
for(var i=0; i<videosInfo.length; i++){
	switch(videosInfo[i].apicode){

		case 'VH8200':
		if(this.domH){
			if(!this.videoControlH82){
				this.videoControlH82 = new Haikang82VideoControl(this.domH);
			}					
		} else {
			if(!this.videoControlH82){
				this.videoControlH82 = new Haikang82VideoControl(containObj,this.wndCountH82);
			}					
		}

		this.videoControlH82.multitudeInit(videosInfo[i],this.wndCountH82);
		break;

		case 'VH1.0':
		if(this.domH){
			if(!this.videoControlH){
				this.videoControlH = new HaikangVideoControl(this.domH);
			}					
		} else {
			if(!this.videoControlH){
				this.videoControlH = new HaikangVideoControl(containObj);
			}					
		}
		
		this.videoControlH.multitudeInit(videosInfo[i],this.wndCountH);
		break;

		case 'VD1.0':
		if(this.domD){
			if(!this.videoControlD){
				this.videoControlD = new DahuaVideoControl(this.domD);
			}										
		} else {
			if(!this.videoControlD){
				this.videoControlD = new DahuaVideoControl(containObj);
			}					
		}				
		this.videoControlD.multitudeInit(videosInfo[i],this.wndCountD);
		break;

		case 'VD5252':
		if(this.domN){
			if(!this.videoControlNVR){
				this.videoControlNVR = new DahuaVideoControlNVR(this.domN);
			}			
		} else {
			if(!this.videoControlNVR){
				this.videoControlNVR = new DahuaVideoControlNVR(containObj);
			}			
		}									
		this.videoControlNVR.init(videosInfo[i],this.wndCountN);
		break;	

		case 'HW1.0':
		alert("暂不支持华为视频!");
		return
		if(this.domHW){
			if(!this.videoControlHW){
				this.videoControlHW = new HuaWeiVideoControl(this.domHW);
			}			
		} else {
			if(!this.videoControlHW){
				this.videoControlHW = new HuaWeiVideoControl(containObj);
			}			
		}									
		this.videoControlHW.init(videosInfo[i],this.wndCountHW);
		break;

		case 'EZVIZ':
			//alert("准备播放萤石云视频!");
			playEZVIZ(containObj,videosInfo[i]);
		break;		

		default :
		this.videoControl = null;
		break;	
	}
}
if(this.domH){
	$("#video-H").hide();
}
if(this.domN){
	$("#video-N").hide();
}
}

videoControlFactory.prototype.getTypeNum = function(arr){
	var obj = {};
	var count = 0;
	for(var i=0; i < arr.length; i++){
		if(!obj[arr[i].apicode]){
			obj[arr[i].apicode] = 1;
			count++;
		}
	}
	return count
}

videoControlFactory.prototype.closeVideo = function(){
	var dh = document.getElementById("DPSDK_OCX");
	var hk = document.getElementById("preview");
	var nvr = document.getElementById("ocx");	
	if(nvr){
		nvr.DisConnectAllChannel();
	}
	if(dh){
		dh.DPSDK_Logout();
	}
}

//控件基类
function VideoControl(containObj){
	
	//videoControlFactory.call(this,containObj);
	
	this._ip = "";
	this._port = "";
	this._userName = "";
	this._passWord = "";
	this._channelNum = "";

	this.isReLogin = false;
	this.LoginSuccess = false;
	this.DahuaOCX = null;
	
	this.gWndId = "";
	this.videoCount = 0;
	this.WndCount = 0;
	this._wndNoH = 0;
	this._wndNoD = 0;

	this.containObj = containObj;
}
VideoControl.prototype.loginPlat = function(deviceInfo){

}
VideoControl.prototype.play = function(deviceInfo){
	
}
VideoControl.prototype.getContextPath = function() { 
	var js=document.scripts;
	var jsRoot;
	for(var i=0;i<js.length;i++){
	 if(js[i].src.indexOf("wdk.js")>-1){
	   jsRoot=js[i].src.substring(0,js[i].src.lastIndexOf("/")+1);
	 }
	}
	return jsRoot
};
VideoControl.prototype.download = function(code){
	var v;
	if(code == 1){
		v = confirm("请点击确认下载大华视频控件,并使用IE浏览器查看视频！");
		if(v){
			window.location.href = this.getContextPath()+"/lib/Lodop6.218/DPSDK_OCX_Win32.exe";
		}
	}

	if(code == 2){
		v = confirm("请点击确认下载海康视频控件\n并使用IE浏览器查看视频！");
		if(v){
			window.location.href = this.getContextPath()+"/lib/Lodop6.218/HikOcx_V6.4.3.3719.exe";
		}
	}  

	if(code == 3) {
		v = confirm("检查到您的海康视频控件不是最新版本\n请点击确认下载最新控件,卸载旧控件,安装新控件后重新查看视频。\n为方面您查看视频，请尽快更新到最新版本HikOcx_V6.4.3.3719");
		if(v){
			window.location.href = this.getContextPath()+"/lib/Lodop6.218/HikOcx_V6.4.3.3719.exe";
		}
	}

	if(code == 4) {
		v = confirm("请点击确认下载大华NVR视频控件\n并使用IE浏览器查看视频!");
		window.location.href = this.getContextPath()+"/lib/Lodop6.218/webplugin.exe";
	}

	if(code == 5) {
		v = confirm("请点击确认下载8200海康视频控件,并使用IE浏览器查看视频！");
		if(v){
			window.location.href = 'https://menheyoss.oss-cn-hangzhou.aliyuncs.com/soft/hkvideo/8200V3.2-V3.3-V3.4.0.exe';
		}
	}		

}

// 海康
function HaikangVideoControl(containObj){
	VideoControl.call(this,containObj);
	this.flagKey = false;
}
HaikangVideoControl.prototype = new VideoControl();

HaikangVideoControl.prototype.loginPlat = function(){

	if(this.LoginSuccess && this.isReLogin){
		return true;
	} else {
		var loginXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><LoginInfo><LoginType>2</LoginType>1<SynLogin>1</SynLogin><IP>"+this._ip+"</IP><Port>"+this._port
		+"</Port><UserName>"+this._userName+"</UserName><Password>"+this._passWord+"</Password></LoginInfo>";

		var resultCode = preview.LoginPlat(loginXML);
		if(resultCode != 0){
			this.LoginSuccess = false;
			alert("登陆失败");
		} else {
			this.LoginSuccess = true;
			return true;
		}
	}		
}

HaikangVideoControl.prototype.multitudeInit = function(deviceInfo,wndCount){ 
		var objHaiKang = document.getElementById('preview');
		if(!objHaiKang){
			this._wndNoH = 0;
			this.containObj.innerHTML ='<object classid="clsid:BE020CC9-521F-4641-85E1-3B631B7ADDD9" id="preview" width="100%" height="100%" name="preview" ></object>';
		}		

		//相同平台海康控件仅仅加载一次
	    if(objHaiKang && this._ip == deviceInfo.ip && this._port == deviceInfo.port && this._userName == deviceInfo.userName && this._passWord == deviceInfo.passWord){
			this.isReLogin = true;
		} else {		
			this.isReLogin = false;		
		}
	    
	    if(this.flagKey){
			return;
		}
	    
		if(!preview.object){			
			this.download(2);
			this.flagKey = true;
			return;
		}
		if(wndCount == 1){
			preview.StopPreview(0);
			this._wndNoH = 0;	
		}

		preview.SetLayoutType(wndCount);

		this._ip = deviceInfo.ip;
		this._port = deviceInfo.port;
		this._userName = deviceInfo.userName;
		this._passWord = deviceInfo.passWord;

		if(this.loginPlat()){			
			this.deviceid =  deviceInfo.deviceid;
			var _param = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Preview><CamIndexCode>"+this.deviceid+"</CamIndexCode></Preview>"; //取流参数
			preview.StartPreviewByIndex(_param,this._wndNoH);
			this._wndNoH++;
			this.startNetTalk();
		}
	}

HaikangVideoControl.prototype.startNetTalk = function(){
	var code = this.deviceid;
	var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><NetTalk><CodeType>1</CodeType><Open>1</Open><DevIndexCode>"+code+"</DevIndexCode><ChanNum>1</ChanNum><CamIndexCode>"+code+"</CamIndexCode><DataDirection>0</DataDirection></NetTalk>"
	var re = preview.NetTalk(xml); //开启控件的网络语音对讲功能 (0 为成功，-1 为失败)
}

//海康8200接口

function Haikang82VideoControl(containObj,wndCount){
	VideoControl.call(this,containObj);
	this.wndCount = wndCount;
	this.wndIndex = 0;
	this.cameraIndexCode = 0;
	this.ip = '';
	this.port = '';
	this.stop = false;
}
Haikang82VideoControl.prototype = new VideoControl();

Haikang82VideoControl.prototype.multitudeInit = function(cameraInfo,wndCount){
	var OCXobj = document.getElementById('PlayViewOCX');
	var _this = this;
	
	if(this.stop){
		return
	}
	if(!OCXobj){
		this.containObj.innerHTML ='<object classid="clsid:04DE0049-8359-486e-9BE7-1144BA270F6A" id="PlayViewOCX"  width="100%" height="100%" name="ocx" ></object>';
		OCXobj = document.getElementById('PlayViewOCX');
		setTimeout(function(){
			if(OCXobj.object){
				_this.initOcx();
				_this.cameraIndexCode = cameraInfo.deviceid;
				_this.ip = cameraInfo.ip;
				_this.port = cameraInfo.port;
				_this.getXmlStr(_this.cameraIndexCode,_this.ip,_this.port);
			} else {
				_this.download(5);
				this.stop = true;
				return
			}			
		},500)				
	}else{
		setTimeout(function(){
			if(OCXobj.object){
				_this.cameraIndexCode = cameraInfo.deviceid;
				_this.ip = cameraInfo.ip;
				_this.port = cameraInfo.port;
				_this.getXmlStr(_this.cameraIndexCode,_this.ip,_this.port);
			} else {
				_this.download(5);
				this.stop = true;
				return
			}			
		},500)			
	}	
}

Haikang82VideoControl.prototype.getXmlStr = function(code,ip,port){
	var _this = this;
	$.ajax({
			url:'wdk?action=obj.hikvision&method=getStreamServiceByCameraIndexCodes' ,
			method:'post',
			data:{
				cameraIndexCodes:code,
				ip:ip,
				port:port
	        },
	        success:function(result){
	        	_this.StartPlayView(result);	        	          					           
		}
		,error:function(result){
		}
		});
}

Haikang82VideoControl.prototype.StartPlayView = function(previewXml){
	var OCXobj = document.getElementById("PlayViewOCX");
	//var curWnd = OCXobj.GetSelWnd();
	var curWnd = this.wndIndex;
	var ret = OCXobj.StartTask_Preview_InWnd(previewXml,curWnd);
	this.wndIndex++;
}

Haikang82VideoControl.prototype.initOcx = function(){
		var OCXobj = document.getElementById("PlayViewOCX");
			OCXobj.SetOcxMode(0); 
			OCXobj.SetWndNum(this.wndCount);  //设置窗口数量
}

//大华
function DahuaVideoControl(containObj){
	VideoControl.call(this,containObj);
}

DahuaVideoControl.prototype = new VideoControl();

DahuaVideoControl.prototype.login = function(deviceInfo){
	if(this.LoginSuccess && this.isReLogin){
		this.isReLogin = false;
		
		var r1 = this.DahuaOCX.DPSDK_LoadDGroupInfo(); // 加载当前登陆用户整个组织设备信息
		if(r1 == 0){
			return true;
		} else {
			alert("加载当前登录用户的组织信息失败！错误码:"+ r1);
			return false;
		}
		
	} else {
		this.loginOut(); 
		var returnCode = this.DahuaOCX.DPSDK_Login(deviceInfo.ip, deviceInfo.port, deviceInfo.userName, deviceInfo.passWord);
		if(returnCode != 0) {
			this.LoginSuccess = false;
			if(returnCode == 3) {
				alert("登录失败，远程设备离线");
				return false;
			}
			alert("登录失败，错误码:"+returnCode);
			return false;
		} else {
			this.LoginSuccess = true;
			return true;
		}			
	}
}
DahuaVideoControl.prototype.multitudeInit =function(deviceInfo,wndCount){

	var h = [];
	this.DahuaOCX = document.getElementById('DPSDK_OCX');
	//大华控件仅仅加载一次
	if(!this.DahuaOCX){
		h.push('<object id="DPSDK_OCX" style="width:100%;height:100%;" classid="CLSID:D3E383B6-765D-448D-9476-DFD8B499926D" codebase="DpsdkOcx.cab#version=1.0.0.0"></object>');
		h = h.join('');
		this.containObj.innerHTML = h;	
	}

	this.DahuaOCX = document.getElementById('DPSDK_OCX');
	
	if(this.DahuaOCX && this.DahuaOCX.object) {
		if(!this.gWndId && this.gWndId != '0'){

			this.gWndId = this.DahuaOCX.DPSDK_CreateSmartWnd(0, 0, 100, 100); // 主窗口号
	    	this.DahuaOCX.DPSDK_SetWndCount(this.gWndId, wndCount); // 设置分屏数量				
	    }

	    if(wndCount == 1){
	    	this._wndNoD = 0;
	    }
	    if(this._ip == deviceInfo.ip && this._port == deviceInfo.port && this._userName == deviceInfo.userName && this._passWord == deviceInfo.passWord){
	    	this.isReLogin = true;
	    }
	    this._ip = deviceInfo.ip;
	    this._port = deviceInfo.port;
	    this._userName = deviceInfo.userName;
	    this._passWord = deviceInfo.passWord;
		//登录大华平台操作
		if(this.login(deviceInfo)){			    			    
			var pkCameraId = deviceInfo.deviceid + "$1$0$" + deviceInfo.channelNum;
			var returnCode =  this.DahuaOCX.DPSDK_StartRealplayByWndNo(this.gWndId, this._wndNoD, pkCameraId, 1, 1, 1);
			this._wndNoD++;
			if(returnCode!=0){
				alert("播放视频失败：" + returnCode);
				return;
			}
		}
	} else {
		this.download(1);
		return;
	}

}

DahuaVideoControl.prototype.loginOut = function(){
	this.DahuaOCX.DPSDK_Logout();
}

//大华NVR,DVR接口类型
function DahuaVideoControlNVR(containObj){
	VideoControl.call(this,containObj);
	var ua = navigator.userAgent.toLowerCase();	
	this.Sys = {};
	this.s;
	(this.s = ua.match(/(msie\s|trident.*rv:)([\d.]+)/)) ? this.Sys.ie = this.s[2] :
	(this.s = ua.match(/firefox\/([\d.]+)/)) ? this.Sys.firefox = this.s[1] :
	(this.s = ua.match(/chrome\/([\d.]+)/)) ? this.Sys.chrome = this.s[1] :
	(this.s = ua.match(/opera.([\d.]+)/)) ? this.Sys.opera = this.s[1] :
	(this.s = ua.match(/version\/([\d.]+).*safari/)) ? this.Sys.safari = this.s[1] : 0;
    this.g_ocx; // 控件对象，初始化完毕后，可以调用控件中的接口
    this.g_curSpeed = 4; // 默认的正常速度
    this.g_PlayTime;
    this.htmlStChn1 = '';
    this.recInfosByFile = [];

}

DahuaVideoControlNVR.prototype = new VideoControl();

DahuaVideoControlNVR.prototype.init = function(deviceInfo,count){
	var succeed = this.loadPageOcx(); // 加载插件到网页中去
	if(succeed){
		this.LoginDevice(deviceInfo);
	}
	

}

DahuaVideoControlNVR.prototype.loadPageOcx = function(){
	var mainOcxHtml = '';
	if (this.Sys.ie) {
		mainOcxHtml = '<object id="ocx" width="100%" height="100%" classid="CLSID:7F9063B6-E081-49DB-9FEC-D72422F2727F"></object>';
	} else {
		mainOcxHtml = '<object id="ocx" width="100%" height="100%" type="application/media-plugin-version-3.1.0.2" VideoWindTextColor="9c9c9c" VideoWindBarColor="414141"></object>';
	}
    //document.getElementById('f_ocx').innerHTML = mainOcxHtml;
    //document.getElementById('Login').style.display = '';
    this.containObj.innerHTML = mainOcxHtml;
    this.g_ocx = document.getElementById('ocx');
    if (this.g_ocx.object) {
    	this.initPageOcx();
    	return true;
    } else {
    	this.download(4);
    	return false;    	
    }

}

DahuaVideoControlNVR.prototype.initPageOcx = function(){
	//TransEvent: 注册这个事件接收控件内部状态
	//这个非常重要，是按时间查找录像查询的关键；调用本例中QueryRecordInfoByTimeEx()会触发回调

	this.g_ocx.AddEventListener('TransEvent', TransEvent);

    //SetNetPlayFileInfo: 注册这个事件接收查询到的录像信息
    //这个非常重要，是录像查询的关键；调用本例中QueryRecord()会触发回调

    this.g_ocx.AddEventListener('SetNetPlayFileInfo', ShowRecInfo);
    this.g_ocx.AddEventListener('NetPlayTimeInform', ShowPlayTime);

    //InsertNetRecordFileInfo: 注册这个事件接收查询到的录像信息
    //这个非常重要，是按时间查找录像查询的关键；调用本例中QueryRecordInfoByTimeEx()会触发回调

    this.g_ocx.AddEventListener('InsertNetRecordFileInfo', InsertNetRecordFileInfo);

    //在这里可以隐藏工具栏上的按钮
    this.hideToolbarBtns();	
}

DahuaVideoControlNVR.prototype.hideToolbarBtns = function(){
    //按钮隐藏可以自由选择怎么设置，遵从此协议格式即可
    //按钮名称有如下几种：{"Fisheye", "ZoomIn", "Record", "CloseVideo", "Snapshot", "Audio"}
    var str = '{"Protocol":"VideoFuncProtocol","Params":{"Audio":false, "Snapshot": false, "Record": false, "Fisheye":false, "ZoomIn":false}}';
    this.g_ocx.ProtocolPluginWithWebCall(str);	
}

DahuaVideoControlNVR.prototype.LoginDevice = function(deviceInfo){
	this._ip = deviceInfo.ip;
	this._port = deviceInfo.port;
	this._userName = deviceInfo.userName;
	this._passWord = deviceInfo.passWord;
	this._channelNum = deviceInfo.channelNum;
	//最后一个参数代表登录方式0：TCP方式登录，1：主动注册方式登入等...
	this.g_ocx.LogoutDevice();
	var bRet = this.g_ocx.LoginDeviceEx(this._ip,this._port,this._userName,this._passWord,0);
	if(bRet == 0){
		this.g_ocx.DisConnectAllChannel(); // 断开所有通道的拉流
		this.RealPlay();
	} else {
		alert("登录失败");
	}
}

DahuaVideoControlNVR.prototype.RealPlay = function(){
	//首先切换到监视模式
    this.g_ocx.SetModuleMode(1); //监视模式	
    //打开通道视频
    this.g_ocx.ConnectRealVideo(this._channelNum,1);
    // 绑定窗口号和通道对应
    this.g_ocx.SetWinBindedChannel(1, 0, 0, 0); 
}

DahuaVideoControlNVR.prototype.StopPlay = function(){
	// 关闭通道视频
	this.g_ocx.DisConnectRealVideo(0); 
}

DahuaVideoControlNVR.prototype.LogoutDevice = function(){
	// 登出设备
	this.g_ocx.LogoutDevice();
}


/**
 * [TransEvent 控件状态事件]
 * @param {[type]} jsonStr		 [状态事件信息字符串]
 */
function TransEvent(jsonStr) {
	//jsonStr格式：'{"EventName" : "xxx", "EventParam" : { ... }}'
	//控件内部的一些状态都会通过该回调上报给js，js根据jsonStr中不同的"EventName"字段判断具体事件
	//如："EventName"=="QueryItemInfo"时，调用本例中QueryRecordInfoByTimeEx()会触发，表示录像查询时返回的总的录像记录条数信息 
	//		{ "EventName" : "QueryItemInfo", 
	//		"EventParam" : { 
	//		"ItemTotal" : 220, 		//总的录像记录条数
	//		"LastItem" : true } }	//true时表示查询结束，false表示查询正在进行中
	//		录像信息比较多时，会分多次接收该事件，直到 "LastItem" 为true
	//
	//"EventName"=="NetPlayState"时，回放模式下切换选中窗口会触发，表示当前窗口的回放状态
	//		{"EventName":"NetPlaySate",
	//		"EventParam":{
	//		"MultiScreeninfo":{"Enable":false,"ShowMode":0},       //4K分屏信息：Enable是否使能，ShowMode显示模式
	//		"channel":2,                                           //通道号
	//		"direction":"normal",                                  //回放方向：normal 正放；backwards倒放
	//		"fisheyeinfo":{"Enable",0},                            // 鱼眼信息：Enable是否使能
	//		"isSwitchwin":true,                                    //该值始终为true
	//		"open":false,                                          //是否正在回放
	//		"speed":4,                                             //回放速度
	//		"state":"stop",                                        //回放状况：play播放，pause暂停，stop关闭，speed快进，preFrame前帧，backFrame后帧，backwards倒放
	//		"winID":0}}                                            //当前窗口号
	//
	//"EventName"=="ReturnWindInfo"时，监视模式下切换选中窗口会触发，表示当前窗口的监视状态
	//document.getElementById('trEvent').value = jsonStr;
}

function ShowRecInfo(nCh, strRecodInfo) {
    /*document.getElementById('PlayBack').style.display = '';
    document.getElementById('PlayRec').style.display = '';
    document.getElementById('PauseRec').style.display = '';
    document.getElementById('FastPlay').style.display = '';
    document.getElementById('SlowPlay').style.display = '';
    document.getElementById('download').style.display = '';
    document.getElementById('RecInfo').style.display = '';
    document.getElementById('ShowPlayTime').style.display = '';
    document.getElementById('DwonLoadPos').style.display = '';
    g_PlayTime = "";
    var readtime = strRecodInfo.split(':');
    var num = readtime.length;
    for (var i = 0; i < num; i++) {
        if (readtime[i] == '')
            continue;
        htmlStChn1 += '<li><a id="StChn' + (i) + '">' + 'channel: ' + nCh + ' info: ' + readtime[i] + '</a></li>';
    }
    document.getElementById('RecInfoList').innerHTML = htmlStChn1;*/
}

//可以得到当前的播放时间, 见g_ocx.AddEventListener('NetPlayTimeInform', ShowPlayTime);
function ShowPlayTime(time) {
   /* //时间的格式00020018|  |是通道分隔符
    g_PlayTime = time;
    document.getElementById('playtime').value = g_PlayTime;*/
}

/**
 * [InsertNetRecordFileInfo 接收新的录像信息：由于录像信息比较多，这里会分多次接收]
 * @param {[type]} nChannel      [录像的通道号]
 * @param {[type]} nEnd          [该通道是否查询完毕]
 * @param {[type]} strRecordInfo [录像信息字符串]
 */
function InsertNetRecordFileInfo(nChannel, nEnd, strRecordInfo) {
    //console.log('InsertNetRecordFileInfo')
    //strRecordInfo格式：2016011120372620160111203741-14-13824-0-00-00-00-19527-00-00:2016011120372620160111203741-14-13824-0-00-00-00-19527-00-00
    //2016011120372620160111203741-14-13824-0-00-00-00-19527-00-00
    //录像时间-录像类型-文件大小-文件索引-码流类型-...
/*    var htmlRecordInfo = '';
    var recInfo = [];
    if (strRecordInfo != '') {
        recInfo = strRecordInfo.split(':');
        var num = recInfo.length;
        for (var i = 0; i < num; i++) {
            if (recInfo[i] == '') {
                continue;
            }
            htmlRecordInfo += '<li><a id="StChn' + (i) + '">' + 'channel: ' + nChannel + ' info: ' + recInfo[i] + '</a></li>';
        }

        document.getElementById('RecInfo').style.display = '';
        document.getElementById('DwonLoadPos').style.display = '';
        document.getElementById('RecInfoList').innerHTML = htmlRecordInfo;
        saveRecordFileInfo(recInfo);
    }*/
}


//华为视频控件
function HuaWeiVideoControl(containObj){
	//继承VideoControl的属性
	VideoControl.call(this,containObj);
}
//使用原型继承VideoControl的方法
HuaWeiVideoControl.prototype = new VideoControl();


HuaWeiVideoControl.prototype.init = function(deviceinfo,wnd){
	var str = '<object id="HWocx" style="width:100%;height: 100%;" classid="CLSID:3556A474-8B23-496F-9E5D-38F7B74654F4"codebase="../ocx/IVS_OCX.cab#version=2,2,0,21">'
            +'<param name="_Version" value="65536" valuetype="data"/>'
            +'<param name="_ExtentX" value="2646" valuetype="data"/>'
            +'<param name="_ExtentY" value="1323" valuetype="data"/>'
            +'<param name="_StockProps" value="0" valuetype="data"/>'
		+'</object>';
	this.containObj.innerHTML = str;
      HWOCX = document.getElementById("HWocx");

    if(HWOCX){
    	//初始化控件
    	this.setInit();
    	//用户登录
    	this.setLogin(deviceinfo);
    	//设置布局
    	this.setLayout(wnd);
    	//开始实时浏览
    	this.getLivePlay(deviceinfo);
    } else {
    	alert("没有初始化HWOCX")
    }
}
/**
 * 初始化华为OCX控件
 */
HuaWeiVideoControl.prototype.setInit = function() {
	if (HWOCX){
		var result = HWOCX.IVS_OCX_Init();
		
		//var path = $("logPath").val();
		var path = "c:/ocxlog/";
		result = HWOCX.IVS_OCX_SetLogPath(path);
		//$("#resultcode").val("IVS_OCX_Init:" +result);
		
		// 设置OCX界面色调： "1"为黑色(暗色调) ，"2"为白色(亮色调)
		HWOCX.IVS_OCX_SetSkin(1);
		
		//// 判断是否支持显卡硬解码
		//result = ocx.IVS_OCX_GetGPUDecodeAbility();
		//if (result == 0)
		//{   
		//	// 关闭显卡硬解码功能
		//	result = ocx.IVS_OCX_EnableGPU(result);
		//}
		
		// 设置OCX显示语言："zh-CN"为中文，"en-US"为英文
		var lang = "";
		if (navigator.language) 
		{
			lang = navigator.language;
		}
		else 
		{
			lang = navigator.browserLanguage;	
		}
		lang = lang.toLowerCase();
		
		if (lang == "zh-cn")
		{
			HWOCX.IVS_OCX_SetLanguage("zh-CN");
		}
		else	
		{
			HWOCX.IVS_OCX_SetLanguage("en-US");
		}
	}	
} 
/**
 * 华为摄像头用户登录
 */
 HuaWeiVideoControl.prototype.setLogin = function(deviceinfo){
 	if(HWOCX)
 	{
 		var user = deviceinfo.userName;
 		var pwd = deviceinfo.passWord;
 		var ip = deviceinfo.ip;
 		var port =deviceinfo.port;

 		var result = HWOCX.IVS_OCX_Login(user, pwd, ip, port, 1);

 		if(result == 0){
			// 如果登录成功，调用设置接收事件回调方法，用于接收服务端事件回调消息
			HWOCX.IVS_OCX_SetEventReceiver(); 			
 		} else {
 			alert("请检查，登录不成功!'</br>'错误码:"+result);
 		}
 	}	
 }
/**
 * 设置华为OCX控件用于播放显示视频的窗格布局
 * @param wndNum 窗格数量
 */
HuaWeiVideoControl.prototype.setLayout = function(wndNum){
	if (HWOCX)
	{
		var result = 0;
		if (wndNum == 1)
		{
			result = HWOCX.IVS_OCX_SetWndLayout(11);  // "11" 代表仅一个窗格布局模式
		}
		else if (wndNum == 6)
		{
			result = HWOCX.IVS_OCX_SetWndLayout(63);  // "63" 代表1大5小布局模式
		}
		else if (wndNum == 9)
		{
			result = HWOCX.IVS_OCX_SetWndLayout(92);  // "92" 代表九宫格布局模式
		}
	}
}
/**
 * 开始浏览实况
 * 说明：开始实况播放操作前，必须先调用设置了播放窗格接口。
 */
HuaWeiVideoControl.prototype.getLivePlay = function(deviceinfo) {
	var cameraCode = deviceinfo.deviceid;
	var wnd = 1;

	var streamType = "1"; //"1"主码流
	var protocolType = "2"; //"1"是UDP,"2"是TCP
	var direstFirst = "1"; //是否直连优先"1"是 "0"否
	var multi = "1";//是否组播"1"是 "0"否 

	var pMediaParaxml = 
			"<?xml version='1.0' encoding='UTF-8'?>" +
		    "<Content>" + 
            "    <RealplayParam>" +
	        "        <StreamType>" +  streamType + "</StreamType>"  + 
		    "        <ProtocolType>" + protocolType + "</ProtocolType>" +
			"        <DirectFirst>" + direstFirst + "</DirectFirst>" + 
	        "        <Multicast>" + multi + "</Multicast>" + 
	        "    </RealplayParam>" + 
	        "</Content>";

	var result = HWOCX.IVS_OCX_StartRealPlay(pMediaParaxml, cameraCode, wnd); 	
}

//萤石云视频
function playEZVIZ(container,deviceInfo) {
	container.innerHTML = '';
	var url = deviceInfo.ip;
	var deviceID = deviceInfo.deviceid;
	var reUrl = url+deviceID;
	//alert(reUrl);
	var str = '<video id="myPlayer" poster="" controls playsInline webkit-playsinline autoplay style="width:100%;height:100%;">'
		     +'<source src="'+reUrl+'"  type="application/x-mpegURL"/>'
	         +'</video>'
	container.innerHTML = str;	
	var player = new EZUIPlayer('myPlayer');
	//var state=0;
	player.on('error', function() {
		console.log('error');
		//state=0;
	});
	player.on('play', function() {
		console.log('play');
		//state=1;
	});
	player.on('pause', function() {
		console.log('pause');
		//state=0;
	});	
}
window.onbeforeunload = function(){
	var obj = document.getElementById("DPSDK_OCX");
	var nvr = document.getElementById("ocx");
	if(obj && obj.object){
		obj.DPSDK_Logout();
	}
	if(nvr && nvr.object){
		nvr.LogoutDevice();
	}
	/**
	 * 退出界面关闭所有资源
	 * Release Ocx Object
	 */	
	//if(HWOCX){
		//var result = HWOCX.IVS_OCX_StopAllRealPlay(); // Stop All Playing Live 
		    //result = HWOCX.IVS_OCX_Logout();          //User Logout		
		    //result = HWOCX.IVS_OCX_CleanUp();	      // Release OCX
		//if(result == 0){
			//alert("退出并释放ocx资源");
		//}
	//}
}




